import 'package:flutter/material.dart';
import '../data/data_service.dart';
import '../entity/game.dart';
import '../entity/view_models/game_detail_data.dart';

class GameDetailProvider extends ChangeNotifier {
  final DataService _dataService = DataService.standard();

  GameDetailData? _gameDetailData;
  GameDetailData? get gameDetailData => _gameDetailData;

  bool _isLoading = true;
  bool get isLoading => _isLoading;

  String? _errorMessage;
  String? get errorMessage => _errorMessage;

  //加载页面所需的所有数据
  //initialGame是从上一个页面传递过来的，已经包含了产品列表
  //获取用户相关的状态（是否在愿望单/库中）
  Future<void> loadGameDetails({
    required Game initialGame,
    required String userId,
  }) async {
    //立即使用传递过来的数据更新UI，避免等待
    _gameDetailData = GameDetailData(game: initialGame, isInWishlist: false, isOwned: false);
    _isLoading = false;
    notifyListeners();

    try {
      //在后台静默获取完整的、包含用户状态的数据包
      final fullData = await _dataService.fetchGameDetailPackage(
        gameId: initialGame.id,
        userId: userId,
      );
      if (fullData != null) {
        _gameDetailData = fullData;
      }
    } catch (e) {
      _errorMessage = "无法加载用户状态: $e";
    } finally {
      //无论成功与否，都再次通知UI更新
      notifyListeners();
    }
  }

  //切换愿望单状态
  Future<void> toggleWishlist(String userId) async {
    if (_gameDetailData == null) return;

    final gameId = _gameDetailData!.game.id;
    final currentlyInWishlist = _gameDetailData!.isInWishlist;

    // 立即更新UI，提供即时反馈
    _gameDetailData = GameDetailData(
      game: _gameDetailData!.game,
      isInWishlist: !currentlyInWishlist, // 状态反转
      isOwned: _gameDetailData!.isOwned,
    );
    notifyListeners();

    try {
      //在后台执行实际的数据库操作
      if (currentlyInWishlist) {
        await _dataService.wishlistRepository.removeFromWishlist(userId, gameId);
      } else {
        await _dataService.wishlistRepository.addToWishlist(userId, gameId);
      }
    } catch (e) {
      //如果操作失败，回滚UI状态并显示错误
      _gameDetailData = GameDetailData(
        game: _gameDetailData!.game,
        isInWishlist: currentlyInWishlist, //恢复原状
        isOwned: _gameDetailData!.isOwned,
      );
      _errorMessage = "操作失败";
      notifyListeners();
    }
  }
}